<?php

namespace app\api\service\alipay;

use app\common\model\Order as OrderModel;
use app\admin\model\Groupdetail;
use app\admin\model\Groupproduct;
use app\admin\model\Member;
use app\admin\model\Orderitem;
use app\admin\model\Rechargerecord;
use app\admin\model\Salesvolume;
use app\api\controller\Integralproduct;
use app\api\service\Detailed;
use app\common\DictConstant;

use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

/**
 * 订单支付回调
 */
class OrderNotify extends BaseNotify
{

    public function notify(){
        $data = $this->alipayNotify();

        // 写入日志
        $postXml = $this->arrayToXml($data);
        Log::record($postXml);

        Db::startTrans();
        try {
            // 验证签名
            if ($data['flag']) {
                // 商户订单号
                $orderNo = $data['out_trade_no'];
                // 交易状态
                $trade_status = $data['trade_status'];
                // 交易付款时间
                $paytime = $data['gmt_payment'];

                if ($trade_status == "TRADE_SUCCESS") {
                    $model = new \app\admin\model\Order();
                    $order = $model->where('order_no', $orderNo)->lock(true)->find();
                    if($order->link_type == 1){
                        //普通订单
                        if($order->status == 1){
                            //写入支付单号
                            $transaction_id = $data['trade_no']; // 64位
                            \app\common\model\Order::where('order_no',$orderNo)->update(['transaction_id'=>$transaction_id,'pay_date'=>$paytime,'pay_method'=>2]);
                            //更新订单状态
                            $this->updateOrderStatus($order->id,$order->link_type);
                            //更新订单占用减库存
                            $this->reduceStock($order->id);
                            //更新销量
                            $this->updatesalesvolume($order->id);
                        }
                    }else{
                        //拼团订单
                        if($order->status == 1){
                            $transaction_id = $data['transaction_id'];
                            \app\common\model\Order::where('order_no',$orderNo)->update(['transaction_id'=>$transaction_id,'pay_date'=>$paytime,'pay_method'=>1]);
                            $this->updateOrderStatus($order->id,$order->link_type);
                            //更新订单占用减库存
                            $this->reduceStock($order->id);
                            $this->updateUserGroupStatus($order->id);
                        }
                    }

                    Db::commit();
                    //改变用户首单立减状态
                    if($order->first_order_reduce >0){
                        Member::where('id',$order->member_id)->update(['isfirst_order_reduce'=>1]);
                    }
                    //会员消费送积分
                    Integralproduct::consumptiongiveintegral($order->member_id,$order->total,$order->id,2);

                    Db::commit();
                    echo "success";
                } else {
                    echo "fail";
                }
            } else {
                echo "fail";
            }
        } catch (Exception $e) {
            Db::rollback();
            Log::record($e->getMessage());
            echo "fail";
        }
    }

    private function reduceStock($orderId){
        $Orderitem = Orderitem::where('order_id',$orderId)->field('product_id,count')->select();
        foreach ($Orderitem as $v){
            db('stock')->where('product_id',$v['product_id'])->setDec('order_stock',$v['count']);
        }
    }

    private function updateOrderStatus($orderID,$linkType){
        $status = DictConstant::OrderPendingDelivery;
        if($linkType == 2){
            //$status = DictConstant::Order_GroupIng;
        }

        OrderModel::where('id','=',$orderID)->update(['status'=>$status]);
        Orderitem::where('order_id',$orderID)->update(['old_status'=>$status]);
    }

    public static function updatesalesvolume($orderId){
        $item = db('order_item')->where('order_id',$orderId)->field('product_id,count')->select();
        if($item){
            $newarr = [];
            foreach ($item as $v){
                $res = Salesvolume::where('product_id',$v['product_id'])->find();
                if($res){
                    $res->setInc('sales_num',$v['count']);
                }else{
                    array_push($newarr,['product_id'=>$v['product_id'],'sales_num'=>$v['count']]);
                }
            }
            if($newarr){
                $model = new Salesvolume();
                $model->saveAll($newarr);
            }
        }
    }

    private function updateUserGroupStatus($orderId){
        $Groupdetail = Groupdetail::where('order_id',$orderId)->find();  //groupproduct
        $Groupproduct = Groupproduct::get($Groupdetail->group_id);
        $chentuannum = $Groupproduct->group_succ_count;
        $oktime = $Groupproduct->group_succ_time;
        if($Groupdetail->member_id == $Groupdetail->originator){
            $endDate = time()+$oktime;
        }else{
            $tuanzhang = Groupdetail::get($Groupdetail->unigroup_id);
            $endDate = $tuanzhang->end_date;
        }
        $goups = Groupdetail::where('unigroup_id',$Groupdetail->unigroupId)->lock(true)->count();
        if($chentuannum > $goups){
            $Groupdetail->end_date = $endDate;
            $Groupdetail->status = 1;
            $Groupdetail->is_pay = 1;
            $Groupdetail->save();
        }elseif ($chentuannum == $goups){
            $allgroups = Groupdetail::where('unigroup_id',$Groupdetail->unigroup_id)->select();
            $list = [];
            foreach ($allgroups as $v){
                array_push($list,['id'=>$v['id'],'status'=>2,'is_pay'=>1,'end_date'=>$endDate]);
            }
            (new Groupdetail())->saveAll($list);
            //把订单里所有该团的状态改为待发货
            $this->updateGroupOrderStatus($Groupdetail->unigroup_id);
            //发送小程序模板消息（先写入队列）

        }else{
            //todo

        }
    }

    private function updateGroupOrderStatus($unigroupId){
        $Groupdetail = Groupdetail::where('unigroup_id',$unigroupId)->select();
        $listorder = [];
        foreach ($Groupdetail as $v){
            $status = DictConstant::OrderPendingDelivery;
            array_push($listorder,['id'=>$v['order_id'],'status'=>$status]);
        }
        $order = new \app\common\model\Order();
        $order->saveAll($listorder);
        $Orderitem = new Orderitem();
        $list = [];
        foreach ($Groupdetail as $value){
            $status = DictConstant::OrderPendingDelivery;
            array_push($list,$value['order_id']);
        }
        $Orderitem->where('order_id','in',$list)->update(['old_status'=>$status]);
    }
}